package com.nari.flutter_desbase64

import android.util.Base64
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.security.SecureRandom
import java.util.zip.GZIPInputStream
import java.util.zip.GZIPOutputStream
import javax.crypto.Cipher
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.DESKeySpec

object DESBase64Util {
    /**
     * 密码长度必须是8的倍数
     */
    const val KEY = "RSAdes123456789whsjzd123"

    /**
     * 加密方式
     */
    const val DES = "DES"

    /**
     * 默认编码
     */
    const val ENCODING = "UTF-8"

    /**
     * DES加密
     *
     * @param src
     * @param key
     * @return
     * @throws Exception
     */
    @Throws(Exception::class)
    fun encrypt(src: ByteArray?, key: ByteArray?): ByteArray {
        // DES算法要求有一个可信任的随机数源
        val sr = SecureRandom()
        // 从原始密匙数据创建DESKeySpec对象
        val dks = DESKeySpec(key)
        // 创建一个密匙工厂，然后用它把DESKeySpec转换成一个SecretKey对象
        val keyFactory = SecretKeyFactory.getInstance(DES)
        val securekey = keyFactory.generateSecret(dks)
        // Cipher对象实际完成加密操作
        val cipher = Cipher.getInstance(DES)
        // 用密匙初始化Cipher对象
        cipher.init(Cipher.ENCRYPT_MODE, securekey, sr)
        // 现在，获取数据并加密
        // 正式执行加密操作
        return cipher.doFinal(src)
    }

    /**
     * DES解密
     *
     * @param src
     * @param key
     * @return
     * @throws Exception
     */
    @Throws(Exception::class)
    fun decrypt(src: ByteArray?, key: ByteArray?): ByteArray {
        // DES算法要求有一个可信任的随机数源
        val sr = SecureRandom.getInstance("SHA1PRNG")
        // 从原始密匙数据创建一个DESKeySpec对象
        val dks = DESKeySpec(key)
        // 创建一个密匙工厂，然后用它把DESKeySpec对象转换成
        // 一个SecretKey对象
        val keyFactory = SecretKeyFactory.getInstance(DES)
        val securekey = keyFactory.generateSecret(dks)
        // Cipher对象实际完成解密操作
        val cipher = Cipher.getInstance(DES)
        // 用密匙初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE, securekey, sr)
        // 现在，获取数据并解密
        // 正式执行解密操作
        return cipher.doFinal(src)
    }

    /**
     * BASE64编码
     *
     * @param info
     * @return
     */
    fun base64Encode(info: ByteArray?): String {
        return Base64.encodeToString(info, Base64.DEFAULT)
    }

    /**
     * BASE64解码
     * *
     *
     * @param info
     * @return
     */
    fun base64Decode(info: String?): ByteArray {
        return Base64.decode(info, Base64.DEFAULT)
    }

    /**
     * 先对消息体进行DES编码再进行BASE64编码
     *
     * @param info
     * @return
     */
    fun encodeInfo(info: String): String {
        try {
            val temp = encrypt(
                info.toByteArray(charset(ENCODING)),
                KEY.toByteArray(charset(ENCODING))
            )
            return base64Encode(temp)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    /**
     * 先对消息体进行BASE64解码再进行DES解码
     *
     * @param info
     * @return
     */
    fun decodeInfo(info: String?): String {
        val temp = base64Decode(info)
        try {
            val buf = decrypt(
                temp,
                KEY.toByteArray(charset(ENCODING))
            )
            return String(buf, Charsets.UTF_8)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    /**
     * 字符串gzip压缩
     */
    fun gzip(primStr: String?): String? {
        if (primStr == null || primStr.length == 0) {
            return primStr
        }
        val out = ByteArrayOutputStream()
        var gzip: GZIPOutputStream? = null
        try {
            gzip = GZIPOutputStream(out)
            gzip.write(primStr.toByteArray())
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            if (gzip != null) {
                try {
                    gzip.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
        return Base64.encodeToString(out.toByteArray(), Base64.DEFAULT)
    }

    /**
     * 字符串的解压
     */
    fun jyZip(compressedStr: String?): String? {
        if (compressedStr == null) {
            return null
        }
        val out = ByteArrayOutputStream()
        var `in`: ByteArrayInputStream? = null
        var ginzip: GZIPInputStream? = null
        var compressed: ByteArray? = null
        var decompressed: String? = null
        try {
            compressed = Base64.decode(compressedStr, Base64.DEFAULT)
            `in` = ByteArrayInputStream(compressed)
            ginzip = GZIPInputStream(`in`)
            val buffer = ByteArray(1024)
            var offset = -1
            while (ginzip.read(buffer).also { offset = it } != -1) {
                out.write(buffer, 0, offset)
            }
            decompressed = out.toString()
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            if (ginzip != null) {
                try {
                    ginzip.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
            if (`in` != null) {
                try {
                    `in`.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
            if (out != null) {
                try {
                    out.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
        return decompressed
    }

    @JvmStatic
    fun jyZipAndDecodeInfo(sourceStr: String?): String? {
        try {
            val jyZipString = jyZip(sourceStr)
            return decodeInfo(jyZipString)
        } catch (exception: Exception) {
            exception.printStackTrace()
        }
        return sourceStr
    }

    fun gZipAndEncodeInfo(sourceStr: String): String? {
        try {
            val encodeString = encodeInfo(sourceStr)
            return gzip(encodeString)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return sourceStr
    }
}